<?php

use SocialiteProviders\Manager\Config;

class ControllerExtensionOauthQqPc extends Controller
{

    const EXTENSION_GROUP = 'oauth';

    const EXTENSION_TYPE = 'qq_pc';

    const SETTING_CODE = self::EXTENSION_GROUP . '_' . self::EXTENSION_TYPE;

    const REDIRECT_URL = 'https://%s/api/v1/app/customer/redirect/%s';

    /**
     * @return array
     * @throws Exception
     */
    public function loginAction()
    {
        $this->load->language('extension/oauth/qq_pc');
        $setting = $this->model_setting_setting->getSetting(self::SETTING_CODE);

		return [
            'type'       => self::EXTENSION_TYPE,
            'title'      => $this->language->get('text_title'),
            'action'     => sprintf(self::REDIRECT_URL, trim(API_HOST, '/'), self::EXTENSION_TYPE),
            'sort_order' => $this->config->get('oauth_wechat_pc_sort_order'),
            'icon'       => image_resize($setting[self::SETTING_CODE . '_icon'], 34, 34)
        ];
	}

    /**
     * PC端的回调处理
     * @see \App\Http\Services\Api\V1\App\Customer\QqService::qqCallback()
     * @throws Exception
     */
    public function callback()
    {
        $customer_id = $this->requestGet('customer_id');
        $token = $this->requestGet('token');
        $type = $this->requestGet('type');
        $oauth_user_id = $this->requestGet('$oauth_user_id');

        if ($customer_id && $token) {
//            $this->customer->loginByCustomerId($customer_id); // 改成 customer
            $this->customer->loginByCustomerIdAndToken($customer_id, $token);

            return $this->url->link('account/login/oauthSuccess');
        } else {
            $query = http_build_query([
                'oauth_type'    => $type,
                'oauth_user_id' => $oauth_user_id,
            ]);

            return $this->url->link('account/register', $query);
        }
	}

    /**
     * @return bool
     *
     * @throws Exception
     */
    public function bindCustomer()
    {
        /** @var ModelExtensionOauthWechatUser $modelOauthUser */
        $modelOauthUser = $this->loadModel('extension/oauth/wechat_user');

        $modelOauthUser->bindCustomer($this->customer->getId(), $this->requestGet('oauth_user_id'));

        return true;
    }
}